package com.atguigu.tingshu.order.template.impl;

import cn.hutool.core.collection.CollUtil;
import com.atguigu.tingshu.album.client.AlbumInfoFeignClient;
import com.atguigu.tingshu.album.client.TrackInfoFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.order.template.OrderConfirmTemplate;
import com.atguigu.tingshu.order.template.TemplateBean;
import com.atguigu.tingshu.vo.order.OrderDetailVo;
import com.atguigu.tingshu.vo.order.OrderInfoVo;
import com.atguigu.tingshu.vo.order.TradeVo;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

@TemplateBean(type = SystemConstant.ORDER_ITEM_TYPE_TRACK)
public class TrackOrderConfirm extends OrderConfirmTemplate {

    @Autowired
    private TrackInfoFeignClient trackInfoFeignClient;

    @Autowired
    private AlbumInfoFeignClient albumInfoFeignClient;

    @Override
    public void trade(OrderInfoVo orderInfoVo, TradeVo tradeVo) {
        Integer trackCount = tradeVo.getTrackCount();
        if (trackCount == 0) throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        // 根据声音id查询专辑信息
        TrackInfo trackInfo = trackInfoFeignClient.getTrackInfo(tradeVo.getItemId()).getData();
        AlbumInfo albumInfo = albumInfoFeignClient.getAlbumInfo(trackInfo.getAlbumId()).getData();
        // 计算价格
        BigDecimal totalAmount = albumInfo.getPrice().multiply(new BigDecimal(trackCount));
        orderInfoVo.setOriginalAmount(totalAmount);
        orderInfoVo.setDerateAmount(new BigDecimal("0.00"));
        orderInfoVo.setOrderAmount(totalAmount);
        // 查询用户本次购买的声音列表
        Result<List<TrackInfo>> userNeedPaidTracksResult = trackInfoFeignClient.findUserNeedPaidTracks(tradeVo.getItemId(), trackCount);
        Assert.notNull(userNeedPaidTracksResult, "查询用户本次购买的声音列表失败");
        List<TrackInfo> userNeedPaidTracks = userNeedPaidTracksResult.getData();
        if (CollUtil.isNotEmpty(userNeedPaidTracks)) {
            // 收集订单明细列表
            List<OrderDetailVo> collect = userNeedPaidTracks.stream().map(item -> OrderDetailVo.builder()
                    .itemId(item.getId())
                    .itemName(item.getTrackTitle())
                    .itemUrl(item.getCoverUrl())
                    .itemPrice(albumInfo.getPrice())
                    .build()
            ).collect(Collectors.toList());
            orderInfoVo.setOrderDetailVoList(collect);
        }
    }
}
